package com.villaday.idf.activity;

import android.content.Intent;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.villaday.idf.R;
import com.villaday.idf.adapter.AddMemberAdapter;
import com.villaday.idf.adapter.SearchMemberRVAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.ClearEditText;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.SideBar;
import com.villaday.idf.custom.UpdateGroupRemarkDialog;
import com.villaday.idf.model.allVipMembersEntity;
import com.villaday.idf.model.vipMembersEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PinyinMemberComparator;
import com.villaday.idf.util.PinyinUtils;
import com.villaday.idf.util.PreferencesUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;

/**
 * 添加组员
 */
public class AddMemberActivity extends BaseActivity implements OkHttpUtil.OnDataListener, OnAdapterCallbackListener, SwipeRefreshLayout.OnRefreshListener, AbsRecyclerViewAdapter.OnItemClickListener
        , SearchMemberRVAdapter.OnAddMemeberFilterListner, UpdateGroupRemarkDialog.OnNoLongRemindListener {

    @BindView(R.id.toolbar_text)
    public Toolbar toolbar;
    @BindView(R.id.toolbar_next)
    public TextView tvNext;
    @BindView(R.id.srl)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.filter_edit)
    public ClearEditText mClearEditText;
    @BindView(R.id.recyclerView)
    public RecyclerView recyclerView;
    @BindView(R.id.sideBar)
    public SideBar sideBar;
    @BindView(R.id.dialog)
    public TextView dialog;
    private AddMemberAdapter recyclerViewAdapter;
    @BindView(R.id.diagIvQuery)
    public ImageView ivSearchIcon;


    LinearLayoutManager manager;
    private List<allVipMembersEntity.BodyBean> dataList = new ArrayList<>();
    private List<allVipMembersEntity.BodyBean> SourceDateList;
    /**
     * 根据拼音来排列RecyclerView里面的数据类
     */
    private PinyinMemberComparator pinyinComparator;
    public static String[] b = {};


    private Gson gson = new GsonBuilder().create();
    private String userId;
    private LoadingDialog loadingDialog;
    private List<allVipMembersEntity.BodyBean> filterDateList;

    private List<allVipMembersEntity.BodyBean> oldGroupMember; //带过来的原数据

    private List<allVipMembersEntity.BodyBean> addMemberList = new ArrayList<>(); //带过来的原数据添加到横排上
    private SearchMemberRVAdapter smAdapter;
    @BindView(R.id.diagRvSel)
    public RecyclerView rvSearchMember;

    String[] arr = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    private String modleId; //传过来的组id(用于匹配是否是该组的成员)
    private boolean isShow;
    public UpdateGroupRemarkDialog updateGroupRemarkDialog;

    @Override
    protected int getViewResId() {
        return R.layout.activity_add_member;
    }

    @Override
    protected void init() {

        String json = getIntent().getStringExtra("data");
        oldGroupMember = gson.fromJson(json, new TypeToken<List<vipMembersEntity.BodyBean>>() {
        }.getType());

//        addMemberList.add(new allVipMembersEntity.BodyBean(1));

        modleId = getIntent().getStringExtra("modleId");
        userId = PreferencesUtil.getUserId(this);
        ToolBarUtil.initToolBar(toolbar, "添加组员", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        }, "", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
//                intent.putExtra("entity", gson.toJson(filterDateList));
                addMemberList.remove(addMemberList.size() - 1);
                intent.putExtra("entity", gson.toJson(addMemberList));
                intent.putExtra("modleId", modleId);
                setResult(RESULT_OK, intent);
                onBackPressed();
            }
        });
        tvNext.setTextColor(getResources().getColor(R.color.colorRed));
        tvNext.setVisibility(View.VISIBLE);
        pinyinComparator = new PinyinMemberComparator();

        //设置右侧SideBar触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = recyclerViewAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position, 0);
                }

            }
        });
//        SourceDateList = filledData(getResources().getStringArray(R.array.date));
//        SourceDateList = filledData(getResources().getStringArray(R.array.date));
//        // 根据a-z进行排序源数据
//        Collections.sort(SourceDateList, pinyinComparator);
        manager = new LinearLayoutManager(this);
//        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerViewAdapter = new AddMemberAdapter(this, this, modleId);
        recyclerViewAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(recyclerViewAdapter);
//        recyclerView.addItemDecoration(new DividerGridItem(this));
        recyclerViewAdapter.setEmptyView(R.layout.empty_add_members);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);


/*        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });*/

        searchMember();
    }


    private void searchMember() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rvSearchMember.setLayoutManager(linearLayoutManager);
        smAdapter = new SearchMemberRVAdapter(this);
        smAdapter.setOnAddMemeberFilterListner(this);
        smAdapter.setFullScreen(true);//设置横向不全屏
        smAdapter.setOnItemClickListener(this);
        rvSearchMember.setAdapter(smAdapter);
        smAdapter.setData(addMemberList);
        smAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                switch (v.getId()) {
                    case R.id.sdv_head: {

                        for (int i = 0; i < filterDateList.size(); i++) {
                            if (addMemberList.get(position).getId().equals(filterDateList.get(i).getId())) {
                                filterDateList.get(i).setSelected(false);
                            }
                        }
                        recyclerViewAdapter.notifyDataSetChanged();
                        addMemberList.remove(position);
                        if (addMemberList.size() <= 1) {
                            ivSearchIcon.setVisibility(View.VISIBLE);
                        }
                        smAdapter.notifyDataSetChanged();
                    }
                    break;
                }
            }
        });
        rvSearchMember.scrollToPosition(smAdapter.getItemCount() - 1);//每次增加一条后RecyclerView滑动到最后
//        linearLayoutManager.scrollToPositionWithOffset(smAdapter.getItemCount() - 2, 0);
    }


    @Override
    protected void loadData() {

        loadingDialog = LoadingDialog.newInstance("加载中...");
        loadingDialog.show(getFragmentManager());
        getData();
    }


    private void getData() {
        Map<String, String> map = new HashMap<>();
        OkHttpUtil.getJSON(this, Constant.URL.all_vip_members, map, this);
    }


    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.all_vip_members.equals(url)) {
                LogeUtil.e("all_vip_members", json);
                dismissLoading();
                allVipMembersEntity vMEntity = gson.fromJson(json, allVipMembersEntity.class);
                dataList.clear();
                if ("200".equals(vMEntity.getCode())) {
                    if (vMEntity.getBody() != null) {
                        dataList.addAll(vMEntity.getBody());
                        //下面都属于下拉刷新时初始化操作
                        addMemberList.clear();
                        addMemberList.add(new allVipMembersEntity.BodyBean(1));
                        smAdapter.notifyDataSetChanged();
                        tvNext.setText("");
                        ivSearchIcon.setVisibility(View.VISIBLE);
                    }
                }
                /**
                 * 把原组员添加进去
                 */
                if (oldGroupMember != null && oldGroupMember.size() > 0) {
                    dataList.addAll(oldGroupMember);
                }
                SourceDateList = filledData(dataList);
                // 根据a-z进行排序源数据
                Collections.sort(SourceDateList, pinyinComparator);

                // 将联系人列表的标题字母放到 List<String>列表中，准备数据去重
                List<String> getLetter = new ArrayList<>();
                for (int i = 0; i < SourceDateList.size(); i++) {
                    getLetter.add(SourceDateList.get(i).getLetters());
                }
                // 数据去重
                getLetter = removeDuplicate(getLetter);
                // 将联系人列表的字母标题排序
                Collections.sort(getLetter, new Comparator<String>() {
                    @Override
                    public int compare(String lhs, String rhs) {
                        return lhs.compareTo(rhs);
                    }
                });

                // 设置已排序好的标题
                if (getLetter.size() > 0) {
                    sideBar.setLetter(getLetter);
                } else {
                    sideBar.setLetter(Arrays.asList(arr));
                }

                filterData("");
            }
        }
    }

    private void addBaseLine() {
/*        if (pageIndex != 1) {
            dataList.add(new TransferRecoredEntity.DataBean.RowsBean(2));
        }*/
    }


    @Override
    public void onFailure(String url, String error) {

    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    @Override
    public void onCallback() {

    }

    @Override
    public void onRefresh() {
        getData();

    }


    /**
     * 为RecyclerView填充数据
     *
     * @param date
     * @return
     */
    private List<allVipMembersEntity.BodyBean> filledData(List<allVipMembersEntity.BodyBean> date) {
        List<allVipMembersEntity.BodyBean> mSortList = new ArrayList<>();

        for (int i = 0; i < date.size(); i++) {
            allVipMembersEntity.BodyBean sortModel = date.get(i);
//            sortModel.setName(date[i]);
            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(date.get(i).getNickName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setLetters(sortString.toUpperCase());
            } else {
                sortModel.setLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新RecyclerView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        filterDateList = new ArrayList<>();
        if (SourceDateList != null && SourceDateList.size() > 0) {

            if (TextUtils.isEmpty(filterStr)) {
                filterDateList = SourceDateList;
            } else {
                filterDateList.clear();
                for (allVipMembersEntity.BodyBean sortModel : SourceDateList) {
                    String name = sortModel.getNickName();
                    if (name.indexOf(filterStr.toString()) != -1 ||
                            PinyinUtils.getFirstSpell(name).startsWith(filterStr.toString())
                            //不区分大小写
                            || PinyinUtils.getFirstSpell(name).toLowerCase().startsWith(filterStr.toString())
                            || PinyinUtils.getFirstSpell(name).toUpperCase().startsWith(filterStr.toString())
                            ) {
                        filterDateList.add(sortModel);
                    }
                }
            }

            // 根据a-z进行排序
            Collections.sort(filterDateList, pinyinComparator);
            if (filterDateList.size() <= 0) {
                recyclerViewAdapter.setEmptyTips(R.id.tv_emptyTips, "没有找到\"" + filterStr + "\"相关搜索结果");
            }
            recyclerViewAdapter.setValue(filterDateList);
            recyclerViewAdapter.setData(filterDateList);

            if (oldGroupMember != null && oldGroupMember.size() > 0) {
                if (caulate(filterDateList) != 0) {
                    tvNext.setText("完成(" + caulate(filterDateList) + ")");
                } else {
                    tvNext.setText("");
                }
            }
        } else {
            if (!TextUtils.isEmpty(filterStr)) {
                recyclerViewAdapter.setEmptyTips(R.id.tv_emptyTips, "没有找到\"" + filterStr + "\"相关搜索结果");
            } else {
                recyclerViewAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");
            }
            recyclerViewAdapter.setValue(filterDateList);
            recyclerViewAdapter.setData(filterDateList);
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        switch (v.getId()) {
            case R.id.iv_choose:
                //如果选择已经是本组成员就不让其点击
                if (!modleId.equals(filterDateList.get(position).getGroup().getId())) {
                    if (isShowUpdateGroupDialog(filterDateList.get(position)) && !filterDateList.get(position).isSelected()) { //是否是其他组成员
                        updateGroupRemarkDialog = UpdateGroupRemarkDialog.newInstance(this, gson.toJson(filterDateList.get(position)));
                        updateGroupRemarkDialog.setOnNoLongRemindListener(this);
                        updateGroupRemarkDialog.show(getFragmentManager());
                    } else {
                        filterDateList.get(position).setSelected(!filterDateList.get(position).isSelected());
                        filterHead(filterDateList.get(position));
                        recyclerViewAdapter.setValue(filterDateList);
                        recyclerViewAdapter.setData(filterDateList);
                        if (caulate(filterDateList) != 0) {
                            tvNext.setText("完成(" + caulate(filterDateList) + ")");
                        } else {
                            if (oldGroupMember != null && oldGroupMember.size() > 0) {
                                tvNext.setText("完成");
                            } else {
                                tvNext.setText("");
                            }
                        }
                    }
                }
                break;

            case R.id.ll_member_layout:
                if (!modleId.equals(filterDateList.get(position).getGroup().getId())) {
//                ToastUtil.initToast(this, filterDateList.get(position).getNickName());
                    if (isShowUpdateGroupDialog(filterDateList.get(position)) && !filterDateList.get(position).isSelected()) { //是否是其他组成员
                        updateGroupRemarkDialog = UpdateGroupRemarkDialog.newInstance(this, gson.toJson(filterDateList.get(position)));
                        updateGroupRemarkDialog.setOnNoLongRemindListener(this);
                        updateGroupRemarkDialog.show(getFragmentManager());
                    } else {
                        filterDateList.get(position).setSelected(!filterDateList.get(position).isSelected());
                        filterHead(filterDateList.get(position));
                        recyclerViewAdapter.setValue(filterDateList);
                        recyclerViewAdapter.setData(filterDateList);
                        if (caulate(filterDateList) != 0) {
                            tvNext.setText("完成(" + caulate(filterDateList) + ")");
                        } else {
                            tvNext.setText("");
                        }
                    }
                }
                break;
        }
    }


    private int caulate(List<allVipMembersEntity.BodyBean> data) {
        int num = 0;
        for (allVipMembersEntity.BodyBean sm : data) {
            if (sm.isSelected()) {
                num = num + 1;
            }
        }
        return num;
    }


    /**
     * 去除重复数据
     *
     * @param list
     * @param <T>
     * @return
     */
    public <T> List<T> removeDuplicate(List<T> list) {
        Set<T> h = new HashSet<>(list);
        list.clear();
        list.addAll(h);
        return list;
    }

    @Override
    public void memberFilter(String s) {
        filterData(s);
    }

    /**
     * 过滤到顶部横排头像
     */

    private void filterHead(allVipMembersEntity.BodyBean bean) {
        if (addMemberList.size() > 1) {
            //先把搜索选项删除，最后再添加
            addMemberList.remove(addMemberList.size() - 1);
            int position = isContain(addMemberList, bean);
            if (position != -1) {//已经被选中过
                if (!bean.isSelected()) {//若已经取消选择，则集合中删除
                    addMemberList.remove(position);
                }
                addMemberList.add(new allVipMembersEntity.BodyBean(1));
                if (addMemberList.size() > 1) { //当为两个对象时做的特殊处理
                    ivSearchIcon.setVisibility(View.GONE);
                } else {
                    ivSearchIcon.setVisibility(View.VISIBLE);
                }

            } else { //表明该集合还未添加过
                if (bean.isSelected()) {//若已经选中，则直接添加到集合当中
                    addMemberList.add(bean);
                }
                addMemberList.add(new allVipMembersEntity.BodyBean(1));
                if (addMemberList.size() > 1) { //当为两个对象时做的特殊处理
                    ivSearchIcon.setVisibility(View.GONE);
                } else {
                    ivSearchIcon.setVisibility(View.VISIBLE);
                }
            }

        } else {
            if (bean.isSelected()) {
                //先把搜索选项删除，最后再添加
                addMemberList.remove(addMemberList.size() - 1);
                addMemberList.add(bean);
                addMemberList.add(new allVipMembersEntity.BodyBean(1));
                if (addMemberList.size() > 1) {//当为两个对象时做的特殊处理
                    ivSearchIcon.setVisibility(View.GONE);

                }

            }

        }
        LogeUtil.e("loge", "addMemberList.size()==" + addMemberList.size());
        smAdapter.notifyDataSetChanged();
    }


    /**
     * 如果包含则返回角标，没有包含直接返回-1
     *
     * @param addMemberList
     * @param bean
     * @return
     */
    public int isContain(List<allVipMembersEntity.BodyBean> addMemberList, allVipMembersEntity.BodyBean bean) {
        for (int i = 0; i < addMemberList.size(); i++) {
            //当为true时， 表明该组员已经添加
            if (bean.getId().equals(addMemberList.get(i).getId())) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void setRemind(boolean remind, allVipMembersEntity.BodyBean bean) {
        isShow = remind;
      /*  addMemberList.add(bean);
        addMemberList.add(new allVipMembersEntity.BodyBean(1));
        if (addMemberList.size() > 1) { //当为两个对象时做的特殊处理
            ivSearchIcon.setVisibility(View.GONE);
        } else {
            ivSearchIcon.setVisibility(View.VISIBLE);
        }*/


        for (int i = 0; i < filterDateList.size(); i++) {
            if (filterDateList.get(i).getId().equals(bean.getId())) {
                filterDateList.get(i).setSelected(!filterDateList.get(i).isSelected());
                filterHead(filterDateList.get(i));
            }
        }
        recyclerViewAdapter.setValue(filterDateList);
        recyclerViewAdapter.setData(filterDateList);
        if (caulate(filterDateList) != 0) {
            tvNext.setText("完成(" + caulate(filterDateList) + ")");
        } else {
            tvNext.setText("");
        }

    }

    public boolean isShowUpdateGroupDialog(allVipMembersEntity.BodyBean bean) {
        if ("默认分组".equals(bean.getGroup().getName())) { //是在默认分组中不弹对话框
            return false;
        } else { //否则根据是否选择不再提示这个字段去做判断
            return !isShow;
        }
    }
}
